package uk.co.lunagroup.xmloperations;

import java.io.File;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLFile {

	public static Vector<FileList> readXMLandReturnVector(final File fXmlFile) {
		Vector<FileList> filesRegister = new Vector<FileList>();

		try {

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();

			System.out.println("Root element :"
					+ doc.getDocumentElement().getNodeName());
			NodeList nList = doc.getElementsByTagName("file");

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;

					filesRegister.addElement(new FileList(getTagValue(
							"xlsPath", eElement), getTagValue("tender",
							eElement), getTagValue("revision", eElement),
							getTagValue("tenderName", eElement)));

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return filesRegister;
	}

	private static String getTagValue(final String sTag, final Element eElement) {
		NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
				.getChildNodes();

		Node nValue = nlList.item(0);

		return nValue.getNodeValue();
	}

	/**
	 * . Returns document from the file
	 * 
	 * @param file
	 * @return document
	 */
	public static Document getDocument(final File file) {
		Document doc = null;
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(file);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;

	}

}